package com.hsmw.api.controller.biz;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.hsmw.api.controller.pub.GaoDUtils;
import com.hsmw.api.controller.pub.TencentPushUtils;
import com.hsmw.api.controller.pub.WebSocket;
import com.hsmw.api.mapper.*;
import com.hsmw.api.service.*;
import com.hsmw.api.utils.GaoDeInfoUtils;
import com.hsmw.api.vo.*;
import com.hsmw.common.base.*;
import com.htn.common.core.base.BusinessType;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.*;
import com.htn.common.core.utils.DateUtil;
import com.htn.common.core.util.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.form.GetObjectByIdForm;
import com.hsmw.domain.form.PublishHsmwOrderForm;
import com.hsmw.domain.vo.HsmwOrderVO;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author WD
 * @since 2021-02-02
 */
@Api(tags = "BIZ-订单管理")
@RestController
@RequestMapping("/api/biz/order")
public class BizOrderController extends BaseController<HsmwUserService, HsmwOrder> {


	@Autowired
	private HsmwOrderService hsmwOrderService;
	@Autowired
	private HsmwItemService hsmwItemService;

	@Autowired
	private HsmwOrderVehicleRelationService hsmwOrderVehicleRelationService;

	@Autowired
	private CurrentHsmwUserUtils currentHsmwUserUtils;

	@Autowired
	private HsmwOrderVehicleRequestService hsmwOrderVehicleRequestService;

	@Autowired
	private  HsmwUserDriverService  hsmwUserDriverService;

	@Autowired
	private HsmwDriverNewsService  hsmwDriverNewsService;

	@Autowired
	private HsmwVehicleService   hsmwVehicleService;

	@Autowired
	private HsmwOrderDistributeInfoService hsmwOrderDistributeInfoService;

	@Autowired
	private HsmwPhoneBindService   hsmwPhoneBindService;

	@Autowired
	private HsmwPictureService hsmwPictureService;


	@Autowired
	private HsmwConcretePlantInfoService hsmwConcretePlantInfoService;


	@Autowired
	private HsmwPumpOperateRecordService hsmwPumpOperateRecordService;



	@Autowired
	private HsmwConcreteOperateRecordService hsmwConcreteOperateRecordService;

	@Autowired
	private HsmwPushInfoService hsmwPushInfoService;

	@Autowired
	private HsmwConcreteOperateService hsmwConcreteOperateService;
	@Autowired
	private WebSocket webSocket;


	@Autowired
	private HsmwPmUserService hsmwPmUserService;

	@Autowired
	private HsmwConcreteUserService hsmwConcreteUserService;

	@Autowired
	private HsmwDriverUserService hsmwDriverUserService;

	@Autowired
	private HsmwBizUserService hsmwBizUserService;

	@Autowired
	private HsmwHtnUserService hsmwHtnUserService;

	@Autowired
	private HsmwTpspUserService hsmwTpspUserService;

	@Autowired
	private HsmwSaleUserService hsmwSaleUserService;


	@Autowired
	private HsmwPmUserMapper hsmwPmUserMapper;

	@Autowired
	private HsmwConcreteUserMapper hsmwConcreteUserMapper;

	@Autowired
	private HsmwDriverUserMapper hsmwDriverUserMapper;

	@Autowired
	private HsmwBizUserMapper hsmwBizUserMapper;

	@Autowired
	private HsmwHtnUserMapper hsmwHtnUserMapper;

	@Autowired
	private HsmwTpspUserMapper hsmwTpspUserMapper;

	@Autowired
	private HsmwSaleUserMapper hsmwSaleUserMapper;

	/**
	 * 分页
	 *
	 * @param basePage
	 * @return
	 */
	@ApiOperation(value = "获取订单分页列表", notes = "获取订单分页列表", produces = "application/json")
	@PostMapping("/getHsmwOrderPage")
	public DataResponse getHsmwOrderPage(@RequestBody @Valid BasePage<HsmwOrder> basePage) {
		IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
		HsmwOrder hsmwOrder = basePage.getRequestData();
		IPage<HsmwOrder> data = hsmwOrderService.getHsmwOrderPage(page, hsmwOrder);
		return new DataResponse(data);
	}

	/**
	 * 获取项目下拉列表
	 *
	 * @param form
	 * @return
	 */
	@ApiOperation(value = "获取项目下拉列表", notes = "获取项目下拉列表  ", produces = "application/json")
	@PostMapping("/getHsmwItemSelect")
	public DataResponse getHsmwItemSelect(@RequestBody GetObjectByIdForm form) {
		List<HsmwItem> data = hsmwItemService.list(Wrappers.lambdaQuery(HsmwItem.class).eq(HsmwItem::getConstructionUnitId, form.getKey()));
		return new DataResponse(data);
	}


	/**
	 * 获取工长下拉列表
	 *
	 * @param form
	 * @return
	 */
	@ApiOperation(value = "获取工长下拉列表", notes = "获取工长下拉列表  ", produces = "application/json")
	@PostMapping("/getForeManSelect")
	public DataResponse getForeManSelect(@RequestBody GetObjectByIdForm form) {
		List<HsmwHtnUser> data = hsmwHtnUserService.list(Wrappers.lambdaQuery(HsmwHtnUser.class)
				.eq(HsmwHtnUser::getConstructionUnitId, form.getKey()));
		return new DataResponse(data);
	}

	/**
	 * 新增
	 * 修改  必须带ID
	 *
	 * @param hsmwOrderVO
	 * @return
	 */
	@ApiOperation(value = "新增/修改订单", notes = "新增/修改订单", produces = "application/json")
	@PostMapping("/saveOrUpdateHsmwOrder")
	public DataResponse saveOrUpdateHsmwOrder(@RequestBody HsmwOrderVO hsmwOrderVO) {
		hsmwOrderService.saveOrUpdateHsmwOrder(hsmwOrderVO);
		return new DataResponse(true);
	}

	/**
	 * 根据ID查询数据
	 * DriverOrderInfoVO
	 *
	 * @param form
	 * @return
	 */
	@ApiOperation(value = "订单详情-根据id查询数据", notes = "订单详情-根据id查询数据", produces = "application/json")
	@PostMapping("/getHsmwOrderById")
	public DataResponse getHsmwOrderById(@RequestBody @Valid GetObjectByIdForm form) {
		HsmwOrderVO hsmwOrderVO = hsmwOrderService.getHsmwOrderById(form.getKey());
		return new DataResponse(hsmwOrderVO);
	}

	/**
	 * 获取订单需求车辆列表
	 *
	 * @param form
	 * @return
	 */
	@ApiOperation(value = "获取订单需求车辆列表", notes = "获取订单需求车辆列表  传参 key：订单id", produces = "application/json")
	@PostMapping("/getRequestVehicleListByOrderId")
	public DataResponse getRequestVehicleListByOrderId(@RequestBody @Valid GetObjectByIdForm form) {
		return new DataResponse(hsmwOrderService.getRequestVehicleListByOrderId(form.getKey()));
	}


	/**
	 * 发布订单
	 *
	 * @param form
	 * @return
	 */
	@ApiOperation(value = "发布订单", notes = "发布订单 ", produces = "application/json")
	@PostMapping("/publishHsmwOrder")
	public DataResponse publishHsmwOrder(@RequestBody @Valid PublishHsmwOrderForm form) {
		//hsmwOrderService.publishHsmwOrder(form);
		return new DataResponse(true);
	}


	/**
	 * 取消订单
	 *
	 * @param form
	 * @return
	 */
	@ApiOperation(value = "取消订单", notes = "取消订单 ", produces = "application/json")
	@PostMapping("/cancelHsmwOrder")
	public DataResponse cancelHsmwOrder(@RequestBody @Valid GetObjectByIdForm form) {
		hsmwOrderService.cancelHsmwOrder(form.getKey());
		return new DataResponse(true);
	}

	/**
	 * @param
	 * @return
	 */
	@ApiOperation(value = "获取字典数据", notes = "获取字典数据", produces = "application/json")
	@GetMapping("/getDictData")
	public DataResponse getOrderCreateInfo() {
		HashMap result = hsmwOrderService.getOrderDictInfo();
		return new DataResponse(result);
	}


	/**
	 * @param
	 * @return
	 */
	@ApiOperation(
			value = "矫正方量",
			notes = "矫正方量",
			response = DataResponse.class)
	@ApiImplicitParams({
			@ApiImplicitParam(
					name = "jsonObject",
					value = "参数说明，id:子订单的id  volume:输入的方量",
					required = true,
					example = "12345"),
	})
	@ApiResponses({
			@ApiResponse(code = 0, message = "操作成功"),
			@ApiResponse(code = 1, message = "更新失败")
	})
	@PostMapping("/correctVolume")
	public DataResponse correctVolume(@RequestBody JSONObject jsonObject) {
		hsmwOrderService.correctVolume(jsonObject.getStr("id"), jsonObject.getStr("volume"));
		return DataResponse.success(true);
	}

	@ApiOperation(value = "获取地理信息", notes = "获取地理信息", produces = "application/json")
	@PostMapping("/getGeoByApi")
	public DataResponse getGeoByApi(@RequestBody GeoReqVO vo) {
		try {
			if(StringUtils.isBlank(vo.getLng())){
				return  new DataResponse("您输入的经度为空，请重新输入！");
			}
			if(StringUtils.isBlank(vo.getLat())){
				return  new DataResponse("您输入的纬度为空，请重新输入！");
			}
			com.alibaba.fastjson.JSONObject object = GaoDUtils.sendGet(vo.getLng(), vo.getLat());
			return DataResponse.success(object);
		}catch (Exception e){
			return DataResponse.failure(500,"获取经纬度信息失败，请重试！");
		}
	}

	@ApiOperation(value = "获取订单各种状态列表", notes = "获取订单各种状态列表", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderStatus",value = "订单状态 等待发布：1 ，进行中：2，已发布：3"),
			@ApiImplicitParam(name = "createName",value = "关键字搜索"),
			@ApiImplicitParam(name = "reachTime",value = "到达时间")
	})
	@PostMapping("/findOrderListByStatus")
	public DataResponse findOrderListByStatus(@RequestBody @Valid BasePage<HsmwOrder> basePage){
		IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
		HsmwOrder hsmwOrder = basePage.getRequestData();
		IPage<HsmwOrder> data = hsmwOrderService.findOrderListByStatus(page, hsmwOrder);
		for (HsmwOrder record : data.getRecords()) {
			String id = record.getId();
			long second = record.getReachTime().toEpochSecond(ZoneOffset.of("+8"));//到达时间
			Long dayMillis = (24L*3600L);
			long newDateMillis = System.currentTimeMillis() / 1000;
			Long millis = second-dayMillis-newDateMillis;
			String s = DateUtil.secToTime(millis.intValue());
			record.setRemainingReleaseTime(s);
			List<HsmwOrderVehicleRelation> list = hsmwOrderVehicleRelationService.list(new LambdaQueryWrapper<HsmwOrderVehicleRelation>().eq(HsmwOrderVehicleRelation::getOrderId, id));
			int size = list.size();
			record.setReceivedNumber(size);
			int reqCount = Integer.valueOf(record.getReqCount()).intValue();//泵车数量
			if(record.getPublishTime() != null){
				long publishTime = record.getPublishTime().toEpochSecond(ZoneOffset.of("+8"));
				long addPublishTime = publishTime + 600L;
				if(size < reqCount && newDateMillis > addPublishTime){
					Long timeOut = newDateMillis-publishTime;
					String timeOutInfo = DateUtil.secToTime(timeOut.intValue());
					record.setTimeOutInfo(timeOutInfo);
				}
			}

			List lists = new ArrayList();
			Double sumDriVolume = 0.00;
			if(CollectionUtil.isNotEmpty(list)){
				for (HsmwOrderVehicleRelation hsmwOrderVehicleRelation : list) {
					Map map = new HashMap();
					String driverName = hsmwOrderVehicleRelation.getDriverName();
					String orderStatus = hsmwOrderVehicleRelation.getOrderStatus();
					map.put("driverName",driverName);
					map.put("orderStatus",orderStatus);
					map.put("force",hsmwOrderVehicleRelation.getForces());
					lists.add(map);
					Double driVolume = Double.valueOf(StringUtils.isBlank(hsmwOrderVehicleRelation.getDriverVolume()) ? "0" : (hsmwOrderVehicleRelation.getDriverVolume()));
					sumDriVolume += driVolume;
				}
			}
			record.setSumDriVolume(sumDriVolume);
			record.setDriverList(lists);
			String createUser = record.getCreateUser();
			HsmwHtnUser hsmwUser = hsmwHtnUserService.getById(createUser);
			record.setUserPhone(hsmwUser.getUsername());
			List<HsmwPicture> hsmwPictures = hsmwPictureService.list(new LambdaQueryWrapper<HsmwPicture>().eq(HsmwPicture::getOrderId, id));
			record.setHsmwPictures(hsmwPictures);
		}
		return new DataResponse(data);
	}

	/*@ApiImplicitParams({
			@ApiImplicitParam(name = "orderSn",value = "订单id",dataType = "String"),
			@ApiImplicitParam(name = "status",value = "订单管理状态，等待发布：wait，进行中：hand，已发布：pub",dataType = "String")
	})
	@ApiOperation(value = "根据订单编号查询车辆信息", notes = "根据订单编号查询车辆信息",produces ="application/json" )
	@PostMapping("findVehicleInfoByOrderSn")
	public DataResponse findVehicleInfoByOrderSn(String orderSn,String status){


		return new DataResponse(hsmwOrderService.findVehicleInfoByOrderSn(orderSn,status));
	}*/


	@ApiOperation(value = "强制关闭订单", notes = "强制关闭订单",produces ="application/json" )
	@ApiImplicitParam(name = "orderId",value = "订单编号",dataType = "String")
	@PostMapping("/forceOffOrder/{orderId}")
	public DataResponse forceOffOrder(@PathVariable("orderId")String orderId){
		if(StringUtils.isBlank(orderId)){
			return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的订单id为空！");
		}
		try {
			HsmwOrder order  =new HsmwOrder();
			order.setId(orderId);
			order.setOrderStatus(OrderStatusEnum.CANCELED.getValue());
			order.setEndTime(LocalDateTime.now());
			order.setRemark("中控强制取消订单！");
			hsmwOrderService.updateById(order);
			//HsmwOrder orderInfo  = hsmwOrderService.getById(orderId);
			List<HsmwDriverNews> news =  new ArrayList<>();
			LambdaQueryWrapper<HsmwOrderVehicleRelation> relationLambdaQueryWrapper = new LambdaQueryWrapper<>();
			relationLambdaQueryWrapper.eq(HsmwOrderVehicleRelation::getOrderId,orderId);
			List<HsmwOrderVehicleRelation> relations = hsmwOrderVehicleRelationService.list(relationLambdaQueryWrapper);
			for(HsmwOrderVehicleRelation relation :relations){
				if(StringUtils.isNotBlank(relation.getDriverId())){
					HsmwUserDriver driver=  hsmwUserDriverService.getById(relation.getDriverId());
					//工长取消成功， 就会往系统消息中插入一条数据
					String msg = "您的编号为"+orderId+"的订单已经被中控强制取消，请知晓！";
					HsmwDriverNews newss = new HsmwDriverNews();
					newss.setMessage(msg);
					newss.setUserId(driver.getUserId());
					newss.setAlreadyRead("0");
					news.add(newss);
					//对APP进行离线推送
					HsmwDriverUser user  = hsmwDriverUserService.getById(driver.getUserId());
					String phoneNum = user.getUsername();
					TencentPushUtils.pushMsg(msg,phoneNum,"order_status_7");
					//将司机改成休息中
					driver.setWorkStatus(CommonConstants.DRIVER_FREE);
					hsmwUserDriverService.updateById(driver);
					//车辆改为空闲中
					HsmwVehicle vehicle =hsmwVehicleService.getVehicleById(relation.getVehicleId());
					vehicle.setWorkStatus(CommonConstants.VEHICLE_FREE);
					hsmwVehicleService.updateById(vehicle);
				/*	//工长取消订单 虚拟号码解绑
					String driverUserName = user.getUsername();
					String foremanUserName =hsmwUser.getUsername();
					HashMap result = new HashMap();
					List<String> phones = new ArrayList<>();
					phones.add(driverUserName);
					phones.add(foremanUserName);
					List<HsmwPhoneBind> binds = hsmwPhoneBindService.list(new LambdaQueryWrapper<HsmwPhoneBind>()
							.eq(HsmwPhoneBind::getOrderId,orderId));
					if(CollectionUtil.isNotEmpty(binds)){
						binds.stream().forEach(hsmwPhoneBind -> {
							XuniTelNumVO vo = new XuniTelNumVO();
							vo.setPoolKey(CommonConstants.POOLKEY_1);
							vo.setSecretNo(hsmwPhoneBind.getSecretNo());
							vo.setSubsId(hsmwPhoneBind.getSubSid());
							IACasClientUtils.unBindAxb(vo);
						});
					}
					//解绑后 删除该订单的相关的隐私号码信息
					hsmwPhoneBindService.remove(new LambdaQueryWrapper<HsmwPhoneBind>().
							eq(HsmwPhoneBind::getOrderId,orderId));*/
				}
			}
			if (StringUtils.isListNotNull(news)){
				hsmwDriverNewsService.saveBatch(news);
			}
			//工长取消订单
			LambdaQueryWrapper<HsmwOrderVehicleRelation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(HsmwOrderVehicleRelation::getOrderId,orderId);
			HsmwOrderVehicleRelation ralation = new HsmwOrderVehicleRelation();
			ralation.setOrderStatus(ChildOrderStatusEnum.CANCELED.getValue());
			hsmwOrderVehicleRelationService.update(ralation,lambdaQueryWrapper);
			LambdaQueryWrapper<HsmwOrderVehicleRequest> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
			lambdaQueryWrapper1.eq(HsmwOrderVehicleRequest::getOrderId,orderId);
			HsmwOrderVehicleRequest request = new HsmwOrderVehicleRequest();
			request.setRequestStatus(ChildOrderStatusEnum.CANCELED.getValue());
			hsmwOrderVehicleRequestService.update(request,lambdaQueryWrapper1);
			//工长取消订单 也应该将 订单发布信息状态变为取消状态。
			HsmwOrderDistributeInfo info = new HsmwOrderDistributeInfo();
			info.setDistributeStatus(DistributeStatusEnum.CANCELED.getValue());
			hsmwOrderDistributeInfoService.update(info,new LambdaQueryWrapper<HsmwOrderDistributeInfo>()
					.eq(HsmwOrderDistributeInfo::getOrderId,orderId));
			return new DataResponse();
		}catch (Exception e){
			e.printStackTrace();
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"取消订单失败，请联系管理员！");
		}
	}

	@ApiOperation(value = "强制关闭泵车订单", notes = "强制关闭订单",produces ="application/json" )
	@ApiImplicitParam(name = "requestId",value = "订单需求编号",dataType = "String")
	@PostMapping("/forceOffPumpOrder/{requestId}")
	public DataResponse forceOffPumpOrder(@PathVariable("requestId")String requestId){
		LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
		if(StringUtils.isBlank(requestId)){
			return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的泵车订单需求id为空！");
		}
		try {
			HsmwOrderVehicleRelation relation =hsmwOrderVehicleRelationService.getOne(new LambdaQueryWrapper<HsmwOrderVehicleRelation>()
					.eq(HsmwOrderVehicleRelation::getOrderVehicleRequestId,requestId));
			if(StringUtils.isNotNull(relation)){
				if(StringUtils.isNotBlank(relation.getDriverId())){
					List<HsmwUserDriver> drivers=  hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>()
							.eq(HsmwUserDriver::getVehicleId,relation.getVehicleId()));
					for(HsmwUserDriver driver :drivers){
						String msg = "您的编号为"+relation.getOrderId()+"的订单已经被中控强制取消，请知晓！";
						//对APP进行离线推送
						HsmwDriverUser user  = hsmwDriverUserService.getById(driver.getUserId());
						String phoneNum = user.getUsername();
						TencentPushUtils.pushMsg(msg,phoneNum,"order_status_7");
						//将司机改成休息中
						driver.setWorkStatus(CommonConstants.DRIVER_FREE);
						hsmwUserDriverService.updateById(driver);
						//车辆改为空闲中
						HsmwVehicle vehicle =hsmwVehicleService.getVehicleById(relation.getVehicleId());
						vehicle.setWorkStatus(CommonConstants.VEHICLE_FREE);
						hsmwVehicleService.updateById(vehicle);
						//工长取消成功， 就会往系统消息中插入一条数据
						HsmwDriverNews newss = new HsmwDriverNews();
						newss.setMessage(msg);
						newss.setUserId(driver.getUserId());
						newss.setAlreadyRead("0");
						hsmwDriverNewsService.save(newss);
					}
				}
				relation.setOrderStatus(ChildOrderStatusEnum.CANCELED.getValue());
				relation.setUpdateUser(loginUser.getId());
				hsmwOrderVehicleRelationService.updateById(relation);
			}
			HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestService.getById(requestId);
			request.setRequestStatus(RequestStatusEnum.CANCELED.getValue());
			request.setUpdateUser(loginUser.getId());
			hsmwOrderVehicleRequestService.updateById(request);
			HsmwPumpOperateRecord record1 = new HsmwPumpOperateRecord();
			record1.setRequestId(request.getId());
			record1.setOrderId(request.getOrderId());
			record1.setCreateTime(LocalDateTime.now());
			record1.setUsername(loginUser.getUsername());
			record1.setOrderStatus(PumpOrderStatusEnum.CANCLED.getValue());
			record1.setOperContent("取消订单！");
			hsmwPumpOperateRecordService.save(record1);

			return new DataResponse();
		}catch (Exception e){
			e.printStackTrace();
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"取消订单失败，请联系管理员！");
		}
	}

	/**
	 * 分页
	 * @param basePage
	 * @return
	 */
	@Log(title = "获取指定状态的泵车 订单列表", businessType = BusinessType.QUERY)
	@ApiOperation(value = "获取指定状态的泵车 订单列表", notes = "获取指定状态的订单列表", produces = "application/json")
	@ApiImplicitParam(name = "orderStatus",value = "订单状态 1：等待接单 2：等待出发 3： 已出发 4： 已到达  6： 已完成 7 已确认 8 已取消",dataType = "String")
		@PostMapping("/getBizOrderListByStatus")
	public DataResponse getUnreceivedOrderList(@RequestBody @Valid BasePage basePage) {
		OrderQueryResultVO data = hsmwOrderService.getHsmwOrderPageByStatus(basePage);
		HashMap result = new HashMap();
		List<BizOrderDTO> orderList = data.getOrderList();
		OrderTotalInfoVO orderTotalInfoVO= data.getOrderTotalInfoVO();
		result.put("total",orderTotalInfoVO.getOrderCount());
		result.put("records",orderList);
		result.put("expectVolumeSum",orderTotalInfoVO.getExpectVolumeSum());
		result.put("driverVolumeSum",orderTotalInfoVO.getDriverVolumeSum());
		return new DataResponse(result);
	}

	/**
	 * 分页
	 * @param orderId
	 * @return
	 */
	@Log(title = "根据参数查询泵车订单列表", businessType = BusinessType.QUERY)
	@ApiOperation(value = "根据参数查询泵车订单列表", notes = "获取指定状态的订单列表", produces = "application/json")
	@ApiImplicitParam(name = "orderStatus",value = "订单状态 1：等待接单 2：等待出发 3： 已出发 4： 已到达  6： 已完成 7 已确认 8 已取消",dataType = "String")
	@PostMapping("/getBizOrderListByparam")
	public DataResponse getBizOrderListByparam(String orderId) {
		OrderQueryResultVO data = hsmwOrderService.getHsmwOrderPageByParam(orderId);
		return new DataResponse(data);
	}


	/**
	 * 分页
	 * @param requestId
	 * @return
	 */
	@Log(title = "获取泵车的操作日志  列表", businessType = BusinessType.QUERY)
	@ApiOperation(value = "获取泵车的操作日志  列表", notes = "获取泵车的操作日志 列表", produces = "application/json")
	@ApiImplicitParam(name = "requestId",value = "订单需求编号",dataType = "String")
	@PostMapping("/getPumpOrderOperList/{requestId}")
	public DataResponse getPumpOrderOperList(@PathVariable("requestId")String requestId) {
		if(StringUtils.isBlank(requestId)){
			return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的泵车订单需求id为空！");
		}
		List<HsmwPumpOperateRecord > data = new ArrayList<>();
		LambdaQueryWrapper<HsmwPumpOperateRecord> lambdaQueryWrapper = new LambdaQueryWrapper<HsmwPumpOperateRecord>();
		HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestService.getById(requestId);
		if(RequestStatusEnum.UNRECEIVED.getValue().equals(request.getRequestStatus())){
			lambdaQueryWrapper.eq(HsmwPumpOperateRecord::getOrderId,request.getOrderId());
			data = hsmwPumpOperateRecordService.list(lambdaQueryWrapper);
		}
		HashMap param = new HashMap();
		param.put("orderId",request.getOrderId());
		param.put("requestId",requestId);
		data = hsmwPumpOperateRecordService.selectHsmwPumpOperateRecords(param);
		return new DataResponse(data);
	}



	/**
	 * 分页

	 * @param basePage
	 * @return
	 */
	@Log(title = "获取外租泵的订单列表", businessType = BusinessType.QUERY)
	@ApiOperation(value = "获取外租泵的订单列表", notes = "获取外租泵的订单列表", produces = "application/json")
	@ApiImplicitParam(name = "orderStatus",value = "订单状态 0：未确认 1：已确认 ",dataType = "String")
	@PostMapping("/getOutLeasingOrderList")
	public DataResponse getOutLeasingOrderList(@RequestBody @Valid BasePage basePage) {
		IPage<OutLeasingOrderVO> data = hsmwOrderService.getOutLeasingOrderList(basePage);
		return new DataResponse(data);
	}




	/**
	 * 分页

	 * @param orderVO
	 * @return
	 */
	@Log(title = "新增外租泵", businessType = BusinessType.QUERY)
	@ApiOperation(value = "新增外租泵", notes = "新增外租泵", produces = "application/json")
	@PostMapping("/addOutLeasingPump")
	public DataResponse addOutLeasingPump(@RequestBody @Valid OutLeasingOrderVO orderVO) {
		return hsmwOrderService.addOutLeasingPump(orderVO);
	}




	/**
	 * @param
	 * @return
	 */
	@Log(title = "中控 确认方量", businessType = BusinessType.INSERT)
	@ApiOperation(value = "中控 确认方量", notes = "中控 确认方量", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "relationId", value = "子订单ID", dataType = "String"),
			@ApiImplicitParam(name = "driverVolume", value = "确认方量", dataType = "String")
	})
	@PostMapping("/ensureVolume")
	public DataResponse ensureVolume(String  relationId,String driverVolume) {
		try {
			LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
			HsmwOrderVehicleRelation hsmwOrderVehicleRelation =hsmwOrderVehicleRelationService.getById(relationId);
			boolean flag = false;
			if(StringUtils.isNotBlank(driverVolume)){
				if(driverVolume.equals(hsmwOrderVehicleRelation.getDriverVolume())){
					flag=true;
				}
			}
			hsmwOrderVehicleRelation.setDriverVolume(driverVolume);
			hsmwOrderVehicleRelation.setDriverVolumeStatus(CommonConstants.YES);
			hsmwOrderVehicleRelationService.updateById(hsmwOrderVehicleRelation);
			StringBuilder content = new StringBuilder();
			if(flag){
				content.append("确认方量有误 修改为: 完成方量"+driverVolume+"m³");
			}else {
				content.append("确认方量无误！");

			}
			HsmwPumpOperateRecord record = new HsmwPumpOperateRecord();
			record.setRelationId(hsmwOrderVehicleRelation.getId());
			record.setOrderStatus(PumpOrderStatusEnum.ENSURE.getValue());
			record.setName(user.getName());
			record.setUserType("调度");
			record.setUsername(user.getUsername());
			record.setCreateTime(LocalDateTime.now());
			record.setOperContent(content.toString());
			hsmwPumpOperateRecordService.save(record);
			return new DataResponse();
		}catch (Exception e){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"确认方量失败，请联系管理员！");
		}
	}



	/**
	 * @param
	 * @return
	 */
	@Log(title = "中控 修改方量", businessType = BusinessType.UPDATE)
	@ApiOperation(value = "中控 修改方量", notes = "中控 修改方量", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "relationId", value = "子订单ID", dataType = "String"),
			@ApiImplicitParam(name = "driverVolume", value = "确认方量", dataType = "String")
	})
	@PostMapping("/updateVolume")
	public DataResponse updateVolume(String  relationId,String driverVolume) {
		try {
			HsmwOrderVehicleRelation hsmwOrderVehicleRelation =hsmwOrderVehicleRelationService.getById(relationId);
			hsmwOrderVehicleRelation.setDriverVolume(driverVolume);
			hsmwOrderVehicleRelationService.updateById(hsmwOrderVehicleRelation);
			return new DataResponse();
		}catch (Exception e){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"确认方量失败，请联系管理员！");
		}
	}


	/**
	 * @param
	 * @return
	 */
	@ApiOperation(value = "中控 获取出发到达的距离和时间", notes = "中控 获取出发到达的距离和时间", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "relationId", value = "子订单ID", dataType = "String")
	})
	@PostMapping("/getDistanceAndTime")
	public DataResponse getDistanceAndTime(String  relationId) {
		try {
			DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			HsmwOrderVehicleRelation hsmwOrderVehicleRelation = hsmwOrderVehicleRelationService.getById(relationId);
			LocalDateTime setoutTime = hsmwOrderVehicleRelation.getSetoutTime();
			LocalDateTime clockInTime = hsmwOrderVehicleRelation.getClockInTime();
			HashMap param = new HashMap();
			param.put("deviceId",hsmwOrderVehicleRelation.getImeiNum());
			param.put("beginTime",dateTimeFormatter.format(setoutTime));
			param.put("endTime",dateTimeFormatter.format(clockInTime));
			com.alibaba.fastjson.JSONObject res = GaoDeInfoUtils.getRecenttravel(param);
			return new DataResponse(res);
		}catch (Exception e){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"获取出发到达的距离和时间失败，请联系管理员！");
		}
	}





	/**
	 * 新增
	 * 修改  必须带ID
	 *
	 * @param
	 * @return
	 */
	@Transactional
	@ApiOperation(value = "帮助签到", notes = "帮助签到", produces = "application/json")
	@ApiImplicitParam(name = "id",value = "订单id",dataType = "String")
	@PostMapping("/signIn")
	public DataResponse signIn( String  relationId) {
		try {
			HsmwOrderVehicleRelation order = hsmwOrderVehicleRelationService.getById(relationId);
			List<HsmwPushInfo> pushs = hsmwPushInfoService.list(new LambdaQueryWrapper<HsmwPushInfo>()
					.eq(HsmwPushInfo::getRelationId, relationId)
					.eq(HsmwPushInfo::getStatus, "0")
					.eq(HsmwPushInfo::getType,"UPDATE_TIME"));
			if(StringUtils.isNotNull(pushs)){
				pushs.stream().forEach(hsmwPushInfo -> {
					hsmwPushInfo.setStatus("1");
					hsmwPushInfoService.updateById(hsmwPushInfo);
				});
			}
			HsmwPumpOperateRecord record = new HsmwPumpOperateRecord();
			record.setOrderId(order.getOrderId());
			record.setVehicleNum(order.getVehicleNum());
			record.setRelationId(relationId);
			record.setRequestId(order.getOrderVehicleRequestId());
			record.setCreateTime(LocalDateTime.now());
			record.setOrderStatus(PumpOrderStatusEnum.STARTUP.getValue());
			DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			HashMap param = new HashMap();
			param.put("device_id",order.getImeiNum());
			param.put("begin_time",dtf.format(order.getSetoutTime()));
			param.put("end_time",dtf.format(LocalDateTime.now()));
			com.alibaba.fastjson.JSONObject result = GaoDeInfoUtils.getRecenttravel(param);
			Integer travelMileage = result.getInteger("travelMileage");
			Integer totalTime = result.getInteger("totalTime");
			int  hour = totalTime/3600;
			int min = (totalTime%3600)/60;
			record.setOperContent("确认到达 行驶"+travelMileage+"公里 用时" +hour+"小时"+min+"分钟" );
			hsmwPumpOperateRecordService.save(record);

			HsmwOrder orderInfo = hsmwOrderService.getById(order.getOrderId());
			HsmwHtnUser foremanUser = hsmwHtnUserService.getById(orderInfo.getCreateUser());
			HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(relationId);
			//进行推送和存入系统消息
			String message = "泵车"+relation.getVehicleNum()+"已到达工地,请及时取得联系";
			String  foremanUserId = orderInfo.getCreateUser();
			String  foremanUsername = foremanUser.getUsername();
			//新增系统消息
			HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
			hsmwDriverNews.setUserId(foremanUserId);
			hsmwDriverNews.setMessage(message);
			hsmwDriverNews.setAlreadyRead("0");
			hsmwDriverNewsService.save(hsmwDriverNews);
			TencentPushUtils.pushForeManMsg(message,foremanUsername,"has_new_message");
			//TencentPushUtils.selfrunMsg(message,foremanUsername,"has_new_message");

			order.setId(relationId);
			order.setReachTime(LocalDateTime.now());
			order.setOrderStatus(ChildOrderStatusEnum.ARRIVED.getValue());
			order.setIfBizSign("1");
			hsmwOrderVehicleRelationService.updateById(order);
			return  new  DataResponse();
		}catch (Exception e){
			e.printStackTrace();
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"帮助签到失败，请联系管理员！");
		}
	}


	/*
	 * 分页
	 *
	 * @param basePage
	 * @return
	 */
	@ApiOperation(value = "搅拌站  散户  项目  获取 混凝土订单 列表 ", notes = "获取 混凝土订单 列表", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "plantId",value = "搅拌站ID 搅拌站查询混凝土订单列表的时候赋值 ",dataType = "String"),
			@ApiImplicitParam(name = "userId",value = "散户ID 散户查询混凝土订单的时候 赋值 ",dataType = "String"),
			@ApiImplicitParam(name = "itemId",value = "项目ID 项目查询混凝土订单的时候 赋值 ",dataType = "String"),
			@ApiImplicitParam(name = "pageNo",value = "当前页   必传",dataType = "String"),
			@ApiImplicitParam(name = "pageSize",value = "每页数量   必传",dataType = "String")
	})
	@PostMapping("/getHsmwConcretePlantOrderList")
	public DataResponse getHsmwConcretePlantOrderList(@RequestBody @Valid BasePage basePage) {
		IPage<ConcreteOrderDTO> data = hsmwConcretePlantInfoService.selectOrderListByParam(basePage);
		return DataResponse.success(data);
	}



	/**
	 * 分页
	 * @param basePage
	 * @return
	 */
	@ApiOperation(value = "项目 +散户 +工长  获取指定状态的泵车订单列表", notes = "获取指定状态的泵车订单列表", produces = "application/json")
	@ApiImplicitParam(name = "orderStatus",value = "订单状态 1：等待接单 2：等待出发 3： 已出发 4： 已到达  6： 已完成 7 已确认 8 已取消",dataType = "String")
	@PostMapping("/getPumpOrderListByStatus")
	public DataResponse getPumpOrderListByStatus(@RequestBody @Valid BasePage basePage) {
		OrderQueryResultVO data = hsmwOrderService.getHsmwOrderPageByStatus(basePage);
		HashMap result = new HashMap();
		List<BizOrderDTO> orderList = data.getOrderList();
		OrderTotalInfoVO orderTotalInfoVO= data.getOrderTotalInfoVO();
		result.put("total",orderTotalInfoVO.getOrderCount());
		result.put("records",orderList);
		result.put("expectVolumeSum",orderTotalInfoVO.getExpectVolumeSum());
		result.put("driverVolumeSum",orderTotalInfoVO.getDriverVolumeSum());
		return new DataResponse(result);
	}



	/**
	 * 分页
	 * @param relationId
	 * @return
	 */
	@ApiOperation(value = "获取泵车的操作日志", notes = "获取泵车的操作日志", produces = "application/json")
	@ApiImplicitParam(name = "relationId",value = "子订单ID",dataType = "String")
	@PostMapping("/getPumpOperrecords")
	public DataResponse getPumpOperrecords(@RequestBody @Valid String relationId) {
		HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(relationId);
		HashMap param = new HashMap();
		param.put("orderId",relation.getOrderId());
		param.put("relationId",relationId);
		List<HsmwPumpOperateRecord > records = hsmwPumpOperateRecordService.selectHsmwPumpOperateRecords(param);
		return new DataResponse(records);
	}


	/**
	 * 分页
	 * @param orderId
	 * @return
	 */
	@ApiOperation(value = "获取混凝土订单的操作日志", notes = "获取泵车的操作日志", produces = "application/json")
	@ApiImplicitParam(name = "orderId",value = "订单ID",dataType = "String")
	@PostMapping("/getConcreteOperatecords")
	public DataResponse getConcreteOperatecords(String orderId) {
		HashMap param = new HashMap();
		param.put("orderId",orderId);
		List<HsmwConcreteOperateRecord> records = hsmwConcreteOperateRecordService.concreteOperateRecordList(param);
		for (HsmwConcreteOperateRecord record :records){
			if(OperTypeEnum.COMMIT.getValue().equals(record.getOperType())){
				List<HsmwConcreteOperate> operates = hsmwConcreteOperateService.list(new LambdaQueryWrapper<HsmwConcreteOperate>()
						.eq(HsmwConcreteOperate::getOrderId,orderId));
				record.setHsmwConcreteOperates(operates);
			}
		}
		return new DataResponse(records);
	}

}

